import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'

const service = axios.create({
  baseURL: "/api", // url = base url + request url
  timeout: 30000 // 超时时间
})

// request interceptor
service.interceptors.request.use(
  config => {
    // 设置公共请求头


    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {

    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.resultcode !== "000000") {
      Message({
        message: res.message || 'Error',
        type: 'error',
        duration: 5 * 1000
      })

      if (res.resultcode === "000002") {
        store.dispatch('user/resetUserId').then(() => {
          location.reload()
        })

      }
      return Promise.reject(new Error(res.message || 'Error'))
    } else {
      return res
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
